package cn.le.utils;

import cn.le.crawler.ipproxy.IpXiCiDailiData;

import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class IpProxyUtil {

    private static List<Proxy> ipProxy = new CopyOnWriteArrayList<>();

    public static void replace(List<Proxy> list){
        ipProxy.clear();
        ipProxy.addAll(list);
    }

    public static List<Proxy> findProxy(){
        return ipProxy;
    }

    protected static final ThreadPoolExecutor executor = new ThreadPoolExecutor(24,24, 10, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(),new ThreadPoolExecutor.CallerRunsPolicy());

    public static List<Proxy> isValid(List<IpXiCiDailiData> list) throws Exception {
        List<Proxy> proxies = new ArrayList<>();
        CompletionService<Proxy> proxyCs = new ExecutorCompletionService<Proxy>(executor);
        for (IpXiCiDailiData data: list) {
            proxyCs.submit(new Callable<Proxy>() {
                @Override
                public Proxy call() throws Exception {
                    try {
                        Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(data.getIp(),data.getPort()));
                        URLConnection httpCon = new URL("https://www.baidu.com/").openConnection(proxy);
                        httpCon.setConnectTimeout(5000);
                        httpCon.setReadTimeout(5000);
                        int code = ((HttpURLConnection) httpCon).getResponseCode();
                        if (code == 200){
                            System.out.println("--------code" + code);
                            return proxy;
                        }
                    }catch (Exception e) {

                    }
                    return null;
                }
            });
        }
        for (int i = 0; i < list.size(); i++) {
            Proxy proxy = proxyCs.take().get();
            if (proxy == null){
                continue;
            }
            proxies.add(proxy);
        }
        return proxies;
    }
}
